package main

import (
	"encoding/json"
	"fmt"
	"github.com/shirou/gopsutil/process"

	"strconv"
)

type Process struct {
	Name   string `json:"name"`   //进程名
	Pid    string `json:"pid"`    //进程id
	Status string `json:"status"` //进程状态
	Memory string `json:"memory"` //进程内存
	Cpu    string `json:"cpu"`    //cpu 占用
}

func main() {
	processq := getProcess()
	js, _ := json.Marshal(processq)
	fmt.Println(string(js))
	p := process.Process{
		Pid: 20352,
	}
	err := p.Kill()
	if err != nil {
		fmt.Println(err)
		return
	}
}

func getProcess() []Process {
	var processq []Process
	p, _ := process.Processes()
	for _, v := range p {
		name, _ := v.Name()
		pid := v.Pid
		status, _ := v.Status()
		memoryInfo, _ := v.MemoryInfo()
		memory := uint64(0)
		if memoryInfo != nil {
			memory = memoryInfo.Data
		}
		cpu, _ := v.CPUPercent()
		processq = append(processq, Process{
			Pid:    fmt.Sprint(pid),
			Name:   name,
			Status: status,
			Memory: strconv.FormatUint(memory, 10),
			Cpu:    strconv.FormatFloat(cpu, 'f', 4, 64),
		})
	}
	return processq

}
